package com.yuanqi.controller;

import com.yuanqi.domain.PaymentRecord;
import com.yuanqi.service.PaymentRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/finance/payment-records")
@CrossOrigin(origins = "*")
public class PaymentRecordController {
    
    @Autowired
    private PaymentRecordService paymentRecordService;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getPaymentRecords(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String paymentNumber,
            @RequestParam(required = false) String orderNumber) {
        
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<PaymentRecord> recordPage = paymentRecordService.getPaymentRecords(pageable, paymentNumber, orderNumber);
            
            if (recordPage.isEmpty() && (paymentNumber != null || orderNumber != null)) {
                List<PaymentRecord> records = paymentRecordService.getPaymentRecordsByConditions(paymentNumber, orderNumber);
                
                Map<String, Object> response = new HashMap<>();
                response.put("content", records);
                response.put("totalElements", records.size());
                response.put("totalPages", 1);
                response.put("currentPage", page);
                response.put("size", size);
                
                return ResponseEntity.ok(response);
            }
            
            List<Map<String, Object>> recordMaps = recordPage.getContent().stream()
                .map(this::convertRecordToMap)
                .toList();
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", recordMaps);
            response.put("totalElements", recordPage.getTotalElements());
            response.put("totalPages", recordPage.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            return ResponseEntity.ok(getMockData(page, size));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getPaymentRecordById(@PathVariable Integer id) {
        try {
            PaymentRecord record = paymentRecordService.getPaymentRecordById(id);
            if (record != null) {
                return ResponseEntity.ok(convertRecordToMap(record));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getPaymentRecordStats() {
        try {
            Map<String, Object> stats = paymentRecordService.getPaymentRecordStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    @PostMapping
    public ResponseEntity<Map<String, Object>> createPaymentRecord(@RequestBody PaymentRecord paymentRecord) {
        try {
            PaymentRecord created = paymentRecordService.createPaymentRecord(paymentRecord);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "付款记录创建成功");
            response.put("data", convertRecordToMap(created));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updatePaymentRecord(@PathVariable Integer id, @RequestBody PaymentRecord paymentRecord) {
        try {
            paymentRecord.setId(id);
            PaymentRecord updated = paymentRecordService.updatePaymentRecord(paymentRecord);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "付款记录更新成功");
            response.put("data", convertRecordToMap(updated));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePaymentRecord(@PathVariable Integer id) {
        try {
            paymentRecordService.deletePaymentRecord(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "付款记录删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    // 私有方法：转换PaymentRecord实体为Map
    private Map<String, Object> convertRecordToMap(PaymentRecord record) {
        Map<String, Object> recordMap = new HashMap<>();
        recordMap.put("id", record.getId());
        recordMap.put("paymentNumber", record.getPaymentNumber());
        recordMap.put("paymentAmount", record.getPaymentAmount());
        recordMap.put("paymentDate", record.getPaymentDate() != null ? record.getPaymentDate().toString() : "");
        recordMap.put("paymentMethod", record.getPaymentMethod());
        recordMap.put("remark", record.getRemark() != null ? record.getRemark() : "");
        recordMap.put("orderType", record.getOrderType());
        recordMap.put("orderNumber", record.getOrderNumber());
        recordMap.put("orderDate", record.getOrderDate() != null ? record.getOrderDate().toString() : "");
        recordMap.put("responsiblePerson", record.getResponsiblePerson());
        recordMap.put("contactPhone", record.getContactPhone());
        recordMap.put("supplierCustomer", record.getSupplierCustomer());
        recordMap.put("totalAmount", record.getTotalAmount());
        recordMap.put("submittedBy", record.getSubmittedBy());
        recordMap.put("submittedTime", record.getSubmittedTime() != null ? record.getSubmittedTime().toString() : "");
        recordMap.put("status", record.getStatus());
        recordMap.put("createTime", record.getCreateTime() != null ? record.getCreateTime().toString() : "");
        return recordMap;
    }
    
    // 获取模拟数据
    private Map<String, Object> getMockData(int page, int size) {
        List<Map<String, Object>> records = List.of(
            createRecordMap(1, "FK001", "3000.00", "2023-01-03", "支付宝", "", "采购单", "CG0001", "2023-02-03", "夏油杰", "13356569878", "5000.00", "3000.00", "夏油杰", "2024-08-23"),
            createRecordMap(2, "FK002", "5000.00", "2023-01-05", "银行转账", "采购预付款", "采购单", "CG0002", "2023-02-05", "五条悟", "14444444444", "8000.00", "8000.00", "五条悟", "2024-08-24"),
            createRecordMap(3, "FK003", "2000.00", "2023-01-07", "现金", "部分付款", "退货单", "TH0001", "2023-02-07", "伏黑惠", "15555555555", "3000.00", "3000.00", "伏黑惠", "2024-08-25")
        );
        
        Map<String, Object> response = new HashMap<>();
        response.put("content", records);
        response.put("totalElements", 3);
        response.put("totalPages", 1);
        response.put("currentPage", page);
        response.put("size", size);
        
        return response;
    }
    
    private Map<String, Object> createRecordMap(Integer id, String paymentNumber, String paymentAmount, String paymentDate, 
                                               String paymentMethod, String remark, String orderType, String orderNumber, 
                                               String orderDate, String responsiblePerson, String contactPhone, 
                                               String supplierCustomer, String totalAmount, String submittedBy, String submittedTime) {
        Map<String, Object> record = new HashMap<>();
        record.put("id", id);
        record.put("paymentNumber", paymentNumber);
        record.put("paymentAmount", paymentAmount);
        record.put("paymentDate", paymentDate);
        record.put("paymentMethod", paymentMethod);
        record.put("remark", remark);
        record.put("orderType", orderType);
        record.put("orderNumber", orderNumber);
        record.put("orderDate", orderDate);
        record.put("responsiblePerson", responsiblePerson);
        record.put("contactPhone", contactPhone);
        record.put("supplierCustomer", supplierCustomer);
        record.put("totalAmount", totalAmount);
        record.put("submittedBy", submittedBy);
        record.put("submittedTime", submittedTime);
        return record;
    }
}
